import router from '@/vue/router/';
import store from '../../vue/vuex/store'

var SIGN_REGEXP = /([yMdhsm])(\1*)/g;
function padding(s, len) {
    var len = len - (s + '').length;
    for (var i = 0; i < len; i++) { s = '0' + s; }
    return s;
};

const goBack = function () {
    if (this.$store.state.fromUrl) {
        router.go(-1)
    } else {
        router.push({ path: '/' })
    }
}



const debounce = (func, wait, immediate) => {
    let timeout, args, context, timestamp, result;
    return function () {
        context = this;
        args = arguments;
        timestamp = new Date();
        const later = () => {
            const last = (new Date()) - timestamp;
            if (last < wait) {
                timeout = setTimeout(later, wait - last);
            } else {
                timeout = null;
                result = func.apply(context, args);
            }
        };
        if (!timeout) {
            timeout = setTimeout(later, wait);
        }
        return result;
    };
}

const throttle = (func, wait, options) => {
    var timeout, context, args, result;
    var previous = 0;
    if (!options) options = {};

    var later = function () {
        previous = options.leading === false ? 0 : new Date();
        timeout = null;
        result = func.apply(context, args);
        if (!timeout) context = args = null; //显示地释放内存，防止内存泄漏
    };

    var throttled = function () {
        var now = new Date();
        if (!previous && options.leading === false) previous = now;
        var remaining = wait - (now - previous);
        context = this;
        args = arguments;
        if (remaining <= 0 || remaining > wait) {
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            previous = now;
            result = func.apply(context, args);
            if (!timeout) context = args = null;
        } else if (!timeout && options.trailing !== false) {
            timeout = setTimeout(later, remaining);
        }
        return result;
    };

    throttled.cancel = function () {
        clearTimeout(timeout);
        previous = 0;
        timeout = context = args = null;
    };
    return throttled;
}

const IsPC = function () {
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
        "SymbianOS", "Windows Phone",
        "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}

const getELTime = function (value, format) {
	if (!value) { return '' }
	// value = value.replace('T', ' ');
	switch (typeof value) {
		case "string":
			value = new Date(value.replace(/-/g, "/"));
			break;
		case "number":
			value = new Date(value);
			break;
	}
	if (!value instanceof Date) return '';
	var dict = {
		"yyyy": value.getFullYear(),
		"MM": ("" + (value.getMonth() + 101)).substr(1),
		"dd": ("" + (value.getDate() + 100)).substr(1),
		"HH": ("" + (value.getHours() + 100)).substr(1),
		"mm": ("" + (value.getMinutes() + 100)).substr(1),
		"ss": ("" + (value.getSeconds() + 100)).substr(1),
		"M": value.getMonth() + 1,
		"d": value.getDate(),
		"H": value.getHours(),
		"m": value.getMinutes(),
		"s": value.getSeconds()

	};
	for (var k in dict) {
		if (format.indexOf(k) >= 0) {
			format = format.replace(k, dict[k]);
		}
	}
	return format;
}

const isAdmin = function(){
    if(!this.$store.state.user.roles){
        return false
    }
    for(let i = 0;i < this.$store.state.user.roles.length;i ++){
        if(this.$store.state.user.roles[i] == 'sysAdmin'){
            return true
        }
    }
    return false
}

const guid  = function(len) {
    //时间戳
    let time = new Date().getTime() + ""
            
    var chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ'.split(''),  
    radix = chars.length,
    qutient = [],
    arr = [];

    //因为时间戳的前几位较为固定 所以将其倒转过来
    qutient = parseInt(time.split("").reverse().join("")); 

    do {
        let mod = qutient % radix;
        qutient = (qutient - mod) / radix;
        arr.unshift(chars[mod]);
    } while (qutient);

    //时间戳生成的62进制最大为八位  不足八位则补足  并在最后一位标记补足的位数
    var num = 0
    for(var i = 0;i < 8 - arr.length;i ++){
        num ++
        arr.push(chars[0 | Math.random()*radix])
    }
    arr.push(num + '')

    //当前arr为9位(1位时间戳+1位标记)
    //生成9位随机字符插入其中
    var guArr = []
    for(var j = 0;j < 9;j ++){
        guArr.push(chars[0 | Math.random()*radix])
        guArr.push(arr[j])
    }

    // 当前guArr为18位
    if(!len || len <= 18){
        //如果小于等于18  则直接返回
    }else{
        //大于18 则要在后面加上随机字符串
        for(var k = 0;k < len - 18;k ++){
            guArr.push(chars[0 | Math.random()*radix])
        }
    }

    return guArr.join('');
}

const guidTime  = function(format) {
    let value = new Date();
    if(!format){
        format = "yyyyMMdd"
    }

	switch (typeof value) {
		case "string":
			value = new Date(value.replace(/-/g, "/"));
			break;
		case "number":
			value = new Date(value);
			break;
	}
	if (!value instanceof Date) return '';
	var dict = {
		"yyyy": value.getFullYear(),
		"MM": ("" + (value.getMonth() + 101)).substr(1),
		"dd": ("" + (value.getDate() + 100)).substr(1),
		"HH": ("" + (value.getHours() + 100)).substr(1),
		"mm": ("" + (value.getMinutes() + 100)).substr(1),
		"ss": ("" + (value.getSeconds() + 100)).substr(1),
		"M": value.getMonth() + 1,
		"d": value.getDate(),
		"H": value.getHours(),
		"m": value.getMinutes(),
		"s": value.getSeconds()

	};
	for (var k in dict) {
		if (format.indexOf(k) >= 0) {
			format = format.replace(k, dict[k]);
		}
	}
	return format;
}

export default {
    install(Vue) {
            Vue.prototype.$goBack = goBack,
            Vue.prototype.$debounce = debounce,
            Vue.prototype.$throttle = throttle,
            Vue.prototype.$IsPC = IsPC,
            Vue.prototype.$getELTime = getELTime,
            Vue.prototype.$isAdmin = isAdmin,
            Vue.prototype.$guid = guid,
            Vue.prototype.$guidTime = guidTime
    },
}
